//登录注册模块
import {reqGetCode, reqLogout, reqUserInfo, reqUserLogin, reqUserRegister} from "@/api";
import {setToken, getToken, clearToken} from "@/utils/token";


const state={
    code:'',
    token:getToken(),
    userInfo:'',
}
const actions={
    //获取验证码
    async getCode(context,phone){
        const result =await reqGetCode(phone);
        if(result.code==200){
            context.commit('GETCODE',result.data)
        }else{
            return Promise.reject(new Error('fail'));
        }
    },
    //用户注册
    async userRegister(context,data){
        const result=await reqUserRegister(data);
        console.log(result)
        if(result.code==200){
            return 'ok'
        }else {
            return Promise.reject(new Error('fail '+result.message));
        }
    },
    //用户登录
    async userLogin(context,data){
        const result=await reqUserLogin(data);
        if(result.code===200){
            context.commit('USERLOGIN',result.data.token)
            //持久化存储token，localStorage
            setToken(result.data.token)
            return 'ok'
        }else {
            return Promise.reject(new Error('fail '+result.message));
        }
    },
    //根据用户token,获取用户信息 token在请求头中
    async getUserInfoByToken(context){
        const result=await reqUserInfo();
        if(result.code==200){
            context.commit('GETUSERINFOBYTOKEN',result.data)
        }else{
            return Promise.reject(new Error(result.message))
        }
    },
    async logout(context){
        const result=await reqLogout();
        if(result.code==200){
            context.commit('LOGOUT');
            return 'ok'
        }else {
            return  Promise.reject(new Error('fail '+result.message))
        }
    }
}
const mutations={
    GETCODE(state,value){
        state.code=value;
    },
    USERLOGIN(state,value){
        state.token=value;
    },
    GETUSERINFOBYTOKEN(state,value){
        state.userInfo=value;
    },
    //退出登录，清除用户信息
    LOGOUT(state){
        state.token=''
        state.userInfo=''
        clearToken()
    }
}
const getters={}

export default {
    state,
    actions,
    mutations,
    getters
}